package com.sd.repay.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;
import java.util.Vector;


public class GlobalInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(GlobalInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        if (handler instanceof HandlerMethod) {
            StringBuilder sb = new StringBuilder();

            HandlerMethod h = (HandlerMethod) handler;
            sb.append("业务类：").append(h.getBean().getClass().getName());
            sb.append("；调用方法：").append(h.getMethod().getName());
            sb.append("；访问参数：").append(getParamString(request.getParameterMap()));
            sb.append("；访问路径：").append(request.getRequestURI());
            log.info("======================================" + sb.toString());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private String getParamString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String[]> e : map.entrySet()) {
            String key = e.getKey();
            sb.append(key).append("=");
            if (ignoreStr(key)) {
                sb.append("******").append("\t");
            } else {
                String[] value = e.getValue();
                if (value != null && value.length == 1) {
                    sb.append(value[0]).append("\t");
                } else {
                    sb.append(Arrays.toString(value)).append("\t");
                }
            }

        }
        return sb.toString();
    }

    /**
     * 过滤敏感值
     *
     * @param key
     * @return
     */
    private boolean ignoreStr(String key) {
        boolean flag = false;
        Vector<String> ignoreKeys = new Vector<>();
        ignoreKeys.add("pwd");
        ignoreKeys.add("password");
        for (String tem : ignoreKeys) {
            if (key.toLowerCase().contains(tem.toLowerCase())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

}
